package com.example.videopublish.activity

import android.app.Activity
import android.content.Intent
import android.database.Cursor
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.videopublish.R
import com.example.videopublish.model.VideoModel
import com.example.videopublish.util.ThumbnailUtils

/**
 * 视频选择活动
 * 允许用户从设备中选择视频文件
 */
class VideoSelectionActivity : AppCompatActivity() {

    private lateinit var videoThumbnailImageView: ImageView
    private lateinit var noVideoSelectedTextView: TextView
    private lateinit var pickVideoButton: Button
    private lateinit var videoInfoTextView: TextView
    private lateinit var nextButton: Button

    private var selectedVideoModel: VideoModel? = null
    private val REQUEST_VIDEO_PICK = 1001

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_video_selection)

        // 初始化视图
        initViews()
        
        // 设置点击事件监听器
        setupClickListeners()
    }

    /**
     * 初始化视图
     */
    private fun initViews() {
        videoThumbnailImageView = findViewById(R.id.videoThumbnailImageView)
        noVideoSelectedTextView = findViewById(R.id.noVideoSelectedTextView)
        pickVideoButton = findViewById(R.id.pickVideoButton)
        videoInfoTextView = findViewById(R.id.videoInfoTextView)
        nextButton = findViewById(R.id.nextButton)

        // 初始状态：未选择视频
        updateUIForNoVideoSelected()
    }

    /**
     * 设置点击事件监听器
     */
    private fun setupClickListeners() {
        // 选择视频按钮
        pickVideoButton.setOnClickListener {
            openVideoGallery()
        }

        // 下一步按钮
        nextButton.setOnClickListener {
            selectedVideoModel?.let { videoModel ->
                // 跳转到视频编辑界面
                val intent = Intent(this, VideoEditActivity::class.java)
                intent.putExtra(VideoEditActivity.EXTRA_VIDEO_URI, videoModel.uri.toString())
                intent.putExtra(VideoEditActivity.EXTRA_VIDEO_DURATION, videoModel.durationMs)
                intent.putExtra(VideoEditActivity.EXTRA_VIDEO_SIZE, videoModel.sizeBytes)
                intent.putExtra(VideoEditActivity.EXTRA_THUMBNAIL_PATH, videoModel.thumbnailPath)
                startActivity(intent)
            }
        }
    }

    /**
     * 打开视频选择器
     */
    private fun openVideoGallery() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(intent, REQUEST_VIDEO_PICK)
    }

    /**
     * 处理视频选择结果
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_VIDEO_PICK && resultCode == Activity.RESULT_OK) {
            data?.data?.let { uri ->
                // 处理选中的视频
                processSelectedVideo(uri)
            }
        }
    }

    /**
     * 处理选中的视频
     * 获取视频信息并更新UI
     */
    private fun processSelectedVideo(uri: Uri) {
        try {
            // 获取视频元数据
            val retriever = MediaMetadataRetriever()
            retriever.setDataSource(this, uri)
            
            // 获取视频时长（毫秒）
            val durationStr = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
            val duration = durationStr?.toLong() ?: 0
            
            // 获取视频大小（字节）
            val cursor = contentResolver.query(uri, arrayOf(MediaStore.Video.Media.SIZE), null, null, null)
            var size: Long = 0
            cursor?.use {
                if (it.moveToFirst()) {
                    size = it.getLong(0)
                }
            }
            
            // 生成缩略图
            val thumbnailBitmap = retriever.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST)
            val thumbnailPath = thumbnailBitmap?.let { 
                ThumbnailUtils.saveBitmapToCache(this, it, "video_thumbnail")
            }
            
            // 创建视频模型
            selectedVideoModel = VideoModel(
                uri = uri,
                durationMs = duration,
                sizeBytes = size,
                thumbnailPath = thumbnailPath
            )
            
            // 更新UI
            updateUIForVideoSelected()
            
            // 释放资源
            retriever.release()
            
        } catch (e: Exception) {
            Toast.makeText(this, "处理视频失败: ${e.message}", Toast.LENGTH_SHORT).show()
            e.printStackTrace()
            updateUIForNoVideoSelected()
        }
    }

    /**
     * 更新UI显示已选择的视频
     */
    private fun updateUIForVideoSelected() {
        selectedVideoModel?.let { videoModel ->
            // 显示缩略图
            videoModel.thumbnailPath?.let { path ->
                videoThumbnailImageView.setImageURI(Uri.parse(path))
            }
            
            // 隐藏"未选择视频"文本
            noVideoSelectedTextView.visibility = View.GONE
            
            // 显示视频信息
            val infoText = StringBuilder()
                .append("时长: ${videoModel.getFormattedDuration()}\n")
                .append("大小: ${videoModel.getFormattedSize()}")
                .toString()
            videoInfoTextView.text = infoText
            
            // 启用"下一步"按钮
            nextButton.isEnabled = true
        }
    }

    /**
     * 更新UI显示未选择视频状态
     */
    private fun updateUIForNoVideoSelected() {
        // 清除缩略图
        videoThumbnailImageView.setImageResource(android.R.drawable.ic_menu_gallery)
        
        // 显示"未选择视频"文本
        noVideoSelectedTextView.visibility = View.VISIBLE
        
        // 重置视频信息
        videoInfoTextView.text = "未选择视频"
        
        // 禁用"下一步"按钮
        nextButton.isEnabled = false
    }
} 